package com.food.config;

import com.food.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        
        try {
            String token = request.getHeader("Authorization");
            logger.debug("Received token: {}", token);
            
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7).trim();
                if (!token.isEmpty()) {
                    logger.debug("Processing token: {}", token);
                    
                    if (JwtUtil.validateToken(token)) {
                        Integer userId = JwtUtil.getUserIdFromToken(token);
                        if (userId != null) {
                            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userId, null, new ArrayList<>());
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                            logger.debug("Authentication set for user: {}", userId);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("JWT Authentication failed: {}", e.getMessage());
        }
        
        chain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getServletPath();
        return path.startsWith("/api/user/login") || 
               path.startsWith("/api/user/register") ||
               path.startsWith("/doc.html") ||
               path.startsWith("/swagger") ||
               path.startsWith("/v2/api-docs") ||
               path.startsWith("/v3/api-docs") ||
               path.startsWith("/webjars");
    }
} 